package org.yogthos;

import org.anddev.andengine.engine.handler.physics.PhysicsHandler;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;

public class Penguin extends AnimatedSprite {
	public final long UPDATE_INTERVAL = 1000;
	private PhysicsHandler physicsHandler;
	private int cameraWidth;
	private int cameraHeight;
	public long lastUpdateTime;
	public long lastTimeFishEaten = 0;
	
	private float acceleration = 15;
	private float deceleration = 0.7f;
	
	public int score = 0;

	public Penguin(int cameraWidth, int cameraHeight, float pX, float pY, float xv, float yv, TiledTextureRegion pTextureRegion) {
		super(pX, pY, pTextureRegion);
		this.physicsHandler = new PhysicsHandler(this);
		this.registerUpdateHandler(this.physicsHandler);
		this.physicsHandler.setVelocity(xv, yv);
		this.cameraHeight = cameraHeight;
		this.cameraWidth = cameraWidth;
		lastUpdateTime = System.currentTimeMillis();
	}

	@Override
	protected void onManagedUpdate(final float pSecondsElapsed) {
		
		float xv = this.physicsHandler.getVelocityX();
		float yv = this.physicsHandler.getVelocityY();

		if(System.currentTimeMillis() - lastTimeFishEaten > UPDATE_INTERVAL) {
			lastTimeFishEaten = 0;
			setCurrentTileIndex(0);
		}
		
		if (this.mX + this.getWidth() > cameraWidth && xv > 0 || this.mX < this.getWidth() && xv < 0)
		{		
			this.physicsHandler.setVelocityX(xv*-1);
		}

		if (this.mY + this.getHeight() > cameraHeight && yv > 0 || this.mY < this.getHeight() && yv < 0)
		{
			this.physicsHandler.setVelocityY(yv*-1);
		}

		long currentTime = System.currentTimeMillis();
		if (currentTime - lastUpdateTime > UPDATE_INTERVAL) {
			
			this.physicsHandler.setVelocity(xv*deceleration, yv*deceleration);
			lastUpdateTime = currentTime;
			
		}
		
		super.onManagedUpdate(pSecondsElapsed);
	}
	
	public void eatFish(Fish fish) {
		score += fish.value;
		setCurrentTileIndex(1);
		lastTimeFishEaten = System.currentTimeMillis();
		
	}
	
	public void updateVelosity(Float xt, Float yt)
	{

        float xv = this.physicsHandler.getVelocityX();
        float yv = this.physicsHandler.getVelocityY();
        
        float xPolar = xt - this.mX;
        float yPolar = yt - this.mY;
        
        double hypotenuse = Math.sqrt(xPolar*xPolar+yPolar*yPolar);
        
        double sin = yPolar/hypotenuse;
        double cos = xPolar/hypotenuse;
        
        this.physicsHandler.setVelocityX((float) (xv+cos*acceleration));
        this.physicsHandler.setVelocityY((float) (yv+sin*acceleration));
	}
}
